<?php

/**
 * Created by PhpStorm.
 * User: fenfen
 * Date: 2016/10/17
 * Time: 18:30
 */
namespace frontend\controllers;

use bc\controller\FrontController;
use bc\model\SpreadModel;
use bc\model\ScanqrcModel;
use bc\model\shop\ShopUserModel;
use bc\util\Util;
use yii\web\Session;
use bc\ar\MActiveRecord;
use bc\wx\OAuth;
use bc\wx\Auth;
use bc\wx\User;

class SpreadController extends FrontController
{
    public $attention = 0;
    public $aview;
	public $userInfop=0;

    /*
     * 初始化
     * */
    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        $session = new Session ();
        $user = $session->get('user');
		if(!$user) {
			$this->setOAuth(OAuth::SNSAPI_USERINFO);
			$user = $session->get('user');
		}

		
		//跳转 暂时关闭推广
//		$this->redirect('/');
		
		$openid = $user ['openid'];

		//判断是否关注
		$this->userInfop = $this->getUserInfo($openid);
        //if ($this->checkUserAttention($openid)) {
		if ($this->userInfop['subscribe']) {
            $this->attention = 1;
        }

		// 生成js sdk签名
        $this->getRequest()->hostInfo;
        $jsConfig = $this->configJsApi();
        $appid = $this->wechat()->appid;
        $secret = $this->wechat()->secret;

        if ($this->attention) {
            $where =  array(
                'openid'=>$openid
            );
            $spreadM = new SpreadModel();
            $spreadR = $spreadM->getRow($where);
            if($spreadR['distributor'] == 3){
                $dao = new MActiveRecord ();
                $sql = "select * from ecs_users left join  wxch_qr on ecs_users.user_id = wxch_qr.binduser where  wxid='" . $openid . "'";
                $row = $dao->getDb ()->createCommand ( $sql )->queryOne ();

                $this->aview ['share_url'] = $this->getRequest()->hostInfo."/spread/share?ticket=".$row['ticket'];
                $this->aview ['share_title'] = '芝士妈妈公益推广计划，各种大奖等你来拿。我来了，你在哪？';
                $this->aview ['share_content'] = '做一个芝士妈妈的推广大使，处处都有好礼等着你。看见没，前方孕育基金正在向你招手，还不快去！';
            }else{
                $this->aview ['share_url'] = $this->getRequest()->hostInfo."/spread/index";
                $this->aview ['share_title'] = '芝士妈妈推广有礼，孕育基金等你领！';
                $this->aview ['share_content'] = '欢迎申请成为芝士妈妈推广大使，母婴潮品享不停，还有各种红包在等你.';
            }
        } else {
            $this->aview ['share_url'] = $this->getRequest()->hostInfo."/spread/index";
            $this->aview ['share_title'] = '芝士妈妈推广有礼，孕育基金等你领！';
            $this->aview ['share_content'] = '欢迎申请成为芝士妈妈推广大使，母婴潮品享不停，还有各种红包在等你.';
        }
        $this->aview ['js_config'] = $jsConfig;
    }

    /**
	 * 活动首页
	 */
	public function actionIndex()
	{
		$session = new Session();
		$user = $session->get('user');
		if(!$user) {
			$this->setOAuth(OAuth::SNSAPI_USERINFO);
			$user = $session->get('user');
		}
			
		$openid = $user ['openid'];
		$spreadModel = new SpreadModel ();
		$row = $spreadModel->getRow ( [
				'openid' => $openid
		] );

		if (empty ( $row ))
		{
			if($this->userInfop['subscribe']) {
				$row = $this->doSpread($openid);
			}
		}
        $row ['attention'] = $this->attention;
		$row ['subscribe'] = $user['subscribe'];
        $row['jsapi'] = $this->aview;

		return $this->render ( 'index', $row );
		
	}
	
	/**
	 * 我的推广
	 */
	public function doSpread($openid)
	{

		//获取用户的微信昵称和头像
		//$userInfo = $this->getUserInfo($openid);
		$data ['headimgurl'] = $this->userInfop['headimgurl'];
		$data ['wx_name'] = $this->userInfop['nickname'];
		$data ['openid'] = $openid;
		// $data['openid'] = 'o8eQSwg3jMbMAD8yE5cx_j9K6E30';
		$data ['name'] = $this->post ( 'name' ); 
		$data ['email'] = $this->post ( 'email' );
		$data ['mobile'] = $this->post ( 'mobile' );
		$data ['agree'] = $this->post ( 'agree' );
		$data ['distributor'] = 1;
		$data ['create_time'] = time ();
		$spreadModel = new SpreadModel ();
		if(!$spreadModel->add ( $data )){
			//数据入库失败
			die();
		}
		
		// 根据openid获取用户的
		$userM = new ShopUserModel ();
        $row = $userM->getRow ( [
            'wxid' => $openid
        ] );
		// 生成二维码
		//$url = 'http://test.wx.zhishimama.com/shop/mobile/api.php';
		$url = $this->getEnv();
		$params ['act'] = 'create_rwm';
		$params ['ac'] = 'ac';
		$params ['id'] = $row ['user_id'];
		
		$rs = Util::httpPost ( $url, $params );
		
		$rdata = $spreadModel->getRow ( [ 
				'openid' => $openid 
		] );
		return $rdata;
	}
	
	/*
	 * 我的推广明细
	 */
	public function actionMyspread()
	{
		$session = new Session ();
		$user = $session->get ( 'user' );
		
		$data ['openid'] = $user ['openid'];
		// $data['openid'] = 'o8eQSwg3jMbMAD8yE5cx_j9K6E30';
		// 根据openid获取用户推广
		
		$where = array (
				'myopenid' => $data ['openid'] 
		);
		
		$wheres = array (
				'myopenid' => $data ['openid'] 
		);
		
		$wherew = array (
				'myopenid' => $data ['openid'],
				'status' => 1 
		);
		
		$scanqrcM = new ScanqrcModel ();
		$scanqrcM->columns = 'id,nickname,create_time,headimgurl';
		$scanqrcM->sort = 'id desc';
		$ScanqrcList = $scanqrcM->getList ( $wherew );
		$ScanqrcsT = $scanqrcM->getTotal ( $wheres );
		$ScanqrcwT = $scanqrcM->getTotal ( $wherew );
        $row ['attention'] = $this->attention;
		$row ['ScanqrcList'] = $ScanqrcList;
		$row ['ScanqrcsT'] = $ScanqrcsT;
		$row ['ScanqrcwT'] = $ScanqrcwT;
		$row['jsapi'] = $this->aview;
		return $this->render ( 'friends', $row );
	}
	
	/**
	 * 推广协议书
	 */
	public function actionRules()
	{
        $this->layout = 'default';
        $session = new Session ();
        $user = $session->get ( 'user' );

        $data ['openid'] = $user ['openid'];
		$spreadModel = new SpreadModel ();
		$row = $spreadModel->getRow ( [
			'openid' => $data ['openid']
		] );
        $row ['attention'] = $this->attention;;
		$row['jsapi'] = $this->aview;
		return $this->render( 'rules',$row );
	}
	
	/*
	 * 生成二维码
	 */
	public function actionQrcode()
	{
		$session = new Session ();
		$user = $session->get ( 'user' );
		
		$data ['openid'] = $user ['openid'];

        //修改生产二维码字段到3
        $where =  array(
            'openid'=>$data ['openid']
        );
        $datatemp = array(
            'distributor' =>3
        );
        $spreadM = new SpreadModel();
        $spreadR = $spreadM->getRow($where);
        $spreadM->modify($datatemp, $spreadR['spread_id']);

		$dao = new MActiveRecord ();
		$sql = "select * from ecs_users left join  wxch_qr on ecs_users.user_id = wxch_qr.binduser where scene like '%推广%' and type = 'tg' and wxid='" . $data ['openid'] . "'";
		$row = $dao->getDb ()->createCommand ( $sql )->queryOne ();

		$this->aview ['share_url'] = $this->getRequest()->hostInfo."/spread/share?ticket=".$row['ticket'];
		$this->aview ['share_title'] = '芝士妈妈推广招募令，各种红包在等你。我来了，你在哪？';
		$this->aview ['share_content'] = '做一个芝士妈妈的推广大使，处处都有好礼等着你。看见没，前方孕育基金正在向你招手，还不快去！';

        $row ['attention'] = $this->attention;;
		$row['jsapi'] = $this->aview;
		return $this->render ( 'qrcode', $row );
	}

	/*
	 * 验证用户是否关注过公众号
	 * */
	public function checkUserAttention($openid)
	{
		if(empty($openid)) return false;
		$userInfo=$this->getUserInfo($openid);
		if(empty($userInfo)){
			return false;
		}else{
			if($userInfo['subscribe'] == 1){
				return true;
			}
			return false;
		}
		return false;
	}

	/*
	 * 获取用户基本信息
	 * */
	public function getUserInfo($openid)
	{
		if($openid)
		{
			$appid = $this->wechat()->appid;
			$secret = $this->wechat()->secret;

			$auth = new Auth($appid, $secret);
			$accessToken = $auth->accessToken;

			$user = new User();

			$info = $user->getUserInfo($accessToken, $openid);
			return $info;
		}
	}

    /*
     * 分享链接
     * */
    public function actionShare()
    {
        $ticket['ticket'] = $this->get('ticket', '');
		$ticket['attention'] = $this->attention;
		$ticket['jsapi'] = $this->aview;
        return $this->render ( 'share', $ticket );
    }

    /*
     * 判断是测试服务器还是正式服务器
     * */
	public function getEnv()
	{
		$serverIpList = ['139.196.243.146'];
		$severIpAddress = $_SERVER['SERVER_ADDR'];
		if(in_array($severIpAddress, $serverIpList))
		{
			//正式环境
			return 'http://wx.zhishimama.com/shop/mobile/api.php';
		}else{
			//测试环境
			return 'http://test.wx.zhishimama.com/shop/mobile/api.php';
		}
	}
}
